<template>
    <el-dialog v-model="show" title="申请对账" width="20%" align-center @close="handleClose">

        <el-row>
            <el-col class="flex" :span="24">
                <div class="label">
                    申请日期：
                </div>
                <div>{{ currentDate }}</div>
            </el-col>
            <el-col class="flex" :span="24">
                <div class="label">
                    所属公司：
                </div>
                <div>{{ props.initList.companyName }}</div>
            </el-col>
            <el-col class="flex" :span="24">
                <div class="label">
                    供应商
                </div>
                <div>{{ props.initList.supplyFactoryName }}</div>
            </el-col>
            <el-col class="flex mb10" :span="24">
                <div class="label">
                    入库金额
                </div>
                <div>￥{{ props.initList.inNumber ? Number(props.initList.inNumber) *
                    Number(props.initList.purchasePrice) : '' }}</div>
            </el-col>
        </el-row>

        <el-form ref="formRef" :model="form" label-width="100px" :rules="rules">
            <!-- <el-form-item label="运费金额：" prop="freight">
                <el-input v-model="form.freight" type="number" placeholder="请输入运费金额" />
            </el-form-item> -->
            <el-form-item label="对账金额：" prop="reconciliationAmount">
                <el-input v-model="form.reconciliationAmount" type="number" placeholder="请输入对账金额" />
            </el-form-item>
            <el-form-item label="对账备注：" prop="remark">
                <el-input v-model="form.remark" type="text" placeholder="请输入对账备注" />
            </el-form-item>  
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button v-loading="loading" @click="handleClose">取 消</el-button>
                <el-button v-loading="loading" type="primary" @click="handleSubmit(formRef)">确 认</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { applyReconciliationApi } from '@/api/sj/purchaseManagement/purchaseOrder';

import type { FormInstance, FormRules } from 'element-plus'
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const props = defineProps(['visible', 'initList']);
const emits = defineEmits(['submit', 'close']);

const show = ref(false);
const loading = ref(false);

watch(() => props.visible, async (newValue) => {
    show.value = newValue
    if (newValue) {
    }
}, { deep: true });

const form = reactive({
    freight: 0,
    reconciliationAmount: '',
    remark: '',
});

const formRef = ref<FormInstance>();

const rules = reactive<FormRules>({
    // freight: [
    //     { required: true, message: '请输入运费金额', trigger: 'blur' },
    // ],
    reconciliationAmount: [
        { required: true, message: '请输入对账金额', trigger: 'blur' },
    ],
});

const handleSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            loading.value = true;
            // 实际金额
            const actualAmount = Number(props.initList.inNumber) *
                Number(props.initList.purchasePrice);

            // 输入金额
            // const inputAmount = form.freight ? Number(form.reconciliationAmount) + Number(form.freight) : Number(form.reconciliationAmount);
            const inputAmount = Number(form.reconciliationAmount);

            // 总差
            const totalDiff = actualAmount - inputAmount;
            console.log(actualAmount, inputAmount, totalDiff, '12312312');

            if (actualAmount != inputAmount) {
                const msg = `实际对账金额${totalDiff > 0 ? '小于' : '大于'}订单总金额，${totalDiff > 0 ? '少' : '多'}了${Math.abs(totalDiff)}元，您确定保存吗？`
                ElMessageBox.confirm(msg, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        putData();
                    })
                    .catch(() => {
                        loading.value = false;

                    });
            } else {
                putData();
            }

        } else {
            console.log('error submit!', fields)
        }
    })
};

/** 数据提交 */
const putData = async () => {
    try {
        const { code } = await applyReconciliationApi({
            orderIds: [props.initList.purchaseInRecordId],
            companyId: props.initList.companyId,
            supplyId: props.initList.supplyFactoryId,
            ...form
        })

        if (code == 200) {
            proxy?.$modal.msgSuccess('操作成功');
            emits('submit', true);
            loading.value = false;

            handleClose();
        }
    } catch (error) {
        loading.value = false;
    }
}


const handleClose = () => {
    formRef.value?.resetFields();
    emits('close');
};

// 计算属性获取当前日期并格式化
const currentDate = computed(() => {
    const date = new Date();
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
});

onMounted(() => {
})
</script>

<style lang="scss" scoped>
.label {
    height: 32px;
    line-height: 32px;
    font-weight: 700;
    display: inline-flex;
    justify-content: flex-end;
    align-items: flex-start;
    padding: 0 12px 0 0;
    box-sizing: border-box;
    flex: 0 0 auto;
    font-size: var(--el-form-label-font-size);
    color: var(--el-text-color-regular);
    width: 100px;
}

.flex {
    display: flex;
    align-items: center;
}
</style>